package zhibi.wechat.mp.extra.base;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import zhibi.frame.springmvc.base.AbstractController;
import zhibi.utils.DateUtils;
import zhibi.utils.IDUtils;
import zhibi.wechat.mp.extra.context.BaseConfig;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class BaseController extends AbstractController implements BaseConfig {
    @Autowired
    private WxMpService wxMpService;

    /**
     * 保存图片
     *
     * @param item
     * @return
     */
    protected String saveImg(MultipartFile item) throws WxErrorException {
        WxMpMaterialService materialService = wxMpService.getMaterialService();
        File file = saveFile2(item);
        WxMpMaterial material = new WxMpMaterial(item.getOriginalFilename(), file, null, null);
        WxMpMaterialUploadResult result = materialService.materialFileUpload("", material);
        return result.getMediaId();
    }


    /**
     * 保存内容图片
     * @param item
     * @return
     * @throws WxErrorException
     */
    protected String saveContentImg(MultipartFile item) throws WxErrorException {
        WxMpMaterialService materialService = wxMpService.getMaterialService();
        File file = saveFile2(item);
        WxMediaImgUploadResult result = materialService.mediaImgUpload(file);
        return result.getUrl();
    }


    /**
     * 保存文件
     *
     * @param item
     * @return
     */
    protected File saveFile2(MultipartFile item) {
        String path = DateUtils.formatDate(new Date(), "yyyy-MM-dd") + "/";
        String fileName = IDUtils.getName() + item.getOriginalFilename();
        File newFile = new File(uploadPath() + path + fileName);
        newFile.getParentFile().mkdirs();
        try {
            newFile.createNewFile();
            item.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFile;
    }
}
